
import { updateUserInfo, removeUserInfo, getUserInfo,updateAppInfo } from '@/utils/cookies'
import { resetRouter } from '@/router'
import {danWS} from '@/utils/danWS';
import Config from '@/config'
const getDefaultState = () => {
  return {
    userInfo:{},
    appInfo:{},
    name: '',
    avatar: '',
    roles:[]
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  UPDATE_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
    
  },
  UPDATE_APP_INFO:(state,appInfo) =>{
    state.appInfo = appInfo;
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { account, password } = userInfo;
    return new Promise((resolve, reject) => {
      login({ account: account.trim(), password: password}).then(data => {
        updateUserInfo(data.userInfo)
        resolve(data.appInfo)
       }).catch(res => {
         console.log(res);
       })
     });
  },
  updateUserInfo({ commit }, userInfo){
    commit('UPDATE_USER_INFO', userInfo);
  },
  updateAppInfo({ commit }, appInfo){
    commit('UPDATE_APP_INFO', appInfo);
    updateAppInfo(appInfo)
  },
  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(data => {
        if (!data) {
          reject('Verification failed, please Login again.')
        }
        const { name, avatar,roles,appInfo} = data
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_ROLES', roles)
        commit('UPDATE_APP_INFO', appInfo)
        //new danWS(Config.websocketUrl + '/?user_type=2&platform_user_id='+state.appInfo.platform_user_id+'&platform_app_id='+state.appInfo.platform_app_id+'&platform_app_user_id='+state.appInfo.platform_app_user_id+'&user_token='+ state.userInfo.user_token);

        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.user).then(() => {
        removeUserInfo() // must remove  token  first
        resetRouter()
        commit('SET_ROLES', [])
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeUserInfo() // must remove  token  first
      commit('SET_ROLES', [])
      commit('RESET_STATE')
      resolve()
    })
  },

   // dynamically modify permissions
   changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setToken(token)
      const { roles } = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

